<template>
	<div class="member-model" memberModel>
		<a-config-provider :locale="locale">
			<a-modal
				:title="isByDepartmentSelect ? '请选择部门' : '请选择人员'"
				:visible="showMember"
				ok-text="确定"
				:after-close="handleAfterClose"
				cancel-text="取消"
				class="confirm-modal select-staff"
				:width="1200"
				:mask-closable="false"
				:confirm-loading="loading"
				@cancel="close"
				@ok="selectMember"
			>
				<div class="member-content">
					<div class="member-table">
						<div class="table-flag">可选择</div>
						<div class="pb10 pl10 pr10">
							<div class="table-search">
								<div class="ml-5px">
									<span class="mr-10px">部门</span>

									<a-tree-select
										ref="treeSelect"
										v-model:value="search.deptId"
										show-search
										style="width: 220px"
										:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
										placeholder="请选择部门"
										allow-clear
										:tree-checkable="isByDepartmentSelect"
										:max-tag-count="0"
										:tree-data="departmentTree"
										:field-names="{
											label: 'name',
											key: 'id',
											value: 'id',
											children: 'children'
										}"
										@change="statusChange"
									>
										<template #maxTagPlaceholder>
											选中部门{{ selectedDepartment.length }}个
										</template>
									</a-tree-select>
								</div>
								<!-- <a-checkbox :checked="isByDepartmentSelect" @change="handleIsByDepartmentSelect">
									选择部门
								</a-checkbox> -->
								<a-input-search
									v-model:value="search.name"
									class="mr-5px"
									:disabled="isByDepartmentSelect"
									placeholder="请输入员工姓名"
									style="width: 250px"
									allow-clear
									@search="statusChange"
								/>
							</div>
							<a-table
								:data-source="tableData"
								row-key="id"
								:row-selection="{ selectedRowKeys: selectedMemberKeys, onChange: onSelectChange }"
								:loading="tableLoading"
								:pagination="false"
								:scroll="{ x: 500, y: 360 }"
								table-layout="fixed"
							>
								<a-table-column key="1" title="员工姓名" width="160px">
									<template #default="{ record }">
										<span>{{ record.name }}（{{ record.jobNo }}）</span>
									</template>
								</a-table-column>
								<a-table-column key="2" title="中心名称" width="150px">
									<template #default="{ record }">
										<span>{{ record.coreName }}</span>
									</template>
								</a-table-column>
								<a-table-column key="3" title="部门名称" width="150px">
									<template #default="{ record }">
										<span>{{ record.deptName }}</span>
									</template>
								</a-table-column>
							</a-table>
							<div class="paging-container">
								<a-pagination
									class="page-btn"
									:current="pagination.current"
									show-size-changer
									:page-size-options="pageSizeOptions"
									show-quick-jumper
									:show-total="(total) => `共 ${total} 条`"
									:total="pagination.total"
									:page-size="pagination.pageSize"
									show-less-items
									@showSizeChange="onShowSizeChange"
									@change="handleTableChange"
								/>
							</div>
						</div>
					</div>
					<div class="member-list">
						<div class="table-flag">已选择</div>
						<div class="selected-view">
							<template v-if="rowSelectionMemberList.length">
								<h4 class="pt10 pb10 pl10 pr10">选择人员</h4>
								<div class="pt10 pb10 pl10 pr10">
									<a-tag
										v-for="tag in rowSelectionMemberList"
										:key="tag.id"
										:closable="true"
										@close="() => handleClose(tag)"
									>
										{{ tag.name }}
									</a-tag>
								</div>
							</template>

							<template v-if="selectedDepartment.length">
								<h4 class="pt10 pb10 pl10 pr10">选择部门</h4>
								<div class="pt10 pb10 pl10 pr10">
									<template>
										<a-tag
											v-for="(tag, index) in selectedDepartment"
											:key="tag.id"
											:closable="true"
											@close="() => handleDelDepartment(index, tag.id)"
										>
											{{ tag.name }}
										</a-tag>
									</template>
								</div>
							</template>
						</div>
					</div>
				</div>
			</a-modal>
		</a-config-provider>
	</div>
</template>

<script>
import { noAuthUserList, getDepartmentTree, setAuthKnowledge } from '../../api/transportManagement';
import zhCNS from 'ant-design-vue/lib/locale-provider/zh_CN';
import { message } from 'ant-design-vue';

export default {
	name: 'MemberModel',
	props: {
		showMember: {
			// 是否显示modal
			type: Boolean
		},
		typeCode: {
			type: Number
		}
	},
	data() {
		return {
			locale: zhCNS,
			test: undefined,
			loading: false,
			tableLoading: false,
			tableData: [],
			departmentTree: [],
			search: {
				name: '',
				deptId: undefined
			},
			selectedMemberKeys: [],
			rowSelectionMemberList: [], // 多选列表
			pageSizeOptions: ['20', '40', '60', '80', '100', '200'],
			pagination: {
				pageSize: 20,
				current: 1,
				total: 0
			},
			// 按部门选择
			isByDepartmentSelect: false,
			// 选中的部门
			selectedDepartment: []
		};
	},
	watch: {
		showMember() {
			if (this.showMember) {
				this.getTableData();
			}
		}
	},
	created() {
		this.getTableData();
		this.getDepartmentTreeList();
	},
	methods: {
		/**
		 * 删除部门
		 * @param {number} index 需要删除的索引
		 * @param {number} id 需删除的id
		 * @returns {void}
		 */
		handleDelDepartment(index, id) {
			const { search, isByDepartmentSelect } = this;

			// 删除右边已选择的部门
			this.selectedDepartment.splice(index, 1);
			// 删除v-model绑定的id 实现和tree-select联动
			const deptIndex = search.deptId.indexOf(id);
			if (deptIndex > -1 && isByDepartmentSelect) {
				search.deptId.splice(deptIndex, 1);
			}
		},

		/**
		 * 是否改变按部门选择
		 * @param {object} e
		 * @returns {void}
		 */
		handleIsByDepartmentSelect(e) {
			const { selectedDepartment, search } = this;
			// 下拉框正在显示，延迟200毫秒，防止select-tree动画卡顿
			const dropdown = document.querySelector('.ant-select-tree-dropdown');
			const time = dropdown && dropdown.style.display === 'none' ? 0 : 200;
			setTimeout(() => {
				// 选中选择部门，把之前已选择的部门勾选到tree-select
				if (e.target.checked) {
					search.deptId = selectedDepartment.map((i) => i.id);
				} else {
					// 清空tree-select已选择得部门，避免与选择员工起冲突
					search.deptId = undefined;
				}

				this.isByDepartmentSelect = e.target.checked;
			}, time);
		},

		getTableData() {
			let { name, deptId } = this.search;
			let { pageSize, current } = this.pagination;
			let params = {
				name,
				deptId,
				typeCode: this.typeCode,
				pageSize,
				pageIndex: current
			};
			this.tableLoading = true;
			noAuthUserList(params)
				.then((res) => {
					this.tableData = res.data.data || [];
					this.pagination.total = res.data.rowCount;
					this.tableLoading = false;
				})
				.catch(() => {
					this.tableLoading = false;
				});
		},
		getDepartmentTreeList() {
			getDepartmentTree()
				.then((res) => {
					this.departmentTree = res.data || [];
				})
				.catch(() => {});
		},
		selectMember() {
			if (!this.rowSelectionMemberList.length && !this.selectedDepartment.length) {
				message.error('请选择员工或部门');
				return;
			}
			this.loading = true;
			let params = {
				userIds: this.rowSelectionMemberList.map((item) => item.id)
			};

			setAuthKnowledge(params.userIds)
				.then((res) => {
					if (res.code == 200) {
						this.loading = false;
						// eslint-disable-next-line vue/require-explicit-emits
						// eslint-disable-next-line vue/custom-event-name-casing
						this.$emit('refreshTable');
						this.$emit('close', false);
					} else {
						this.loading = false;
						message.error('新增失败');
					}
					console.log('1111111');
				})
				.catch(() => {
					this.loading = false;
				});
		},

		getAppointDepat(extra) {
			var selectedDepartment = [];
			for (const item of extra.allCheckedNodes) {
				const { name, id } = item.node.data.props;
				selectedDepartment.push({ id, name });
				if (item.children && item.children.length) {
					selectedDepartment.push(...this.getAppointDepat({ allCheckedNodes: item.children }));
				}
			}

			return selectedDepartment;
		},

		statusChange(value) {
			// 按部门选择
			if (this.isByDepartmentSelect) {
				this.selectedDepartment = this.getAppointDepat(value);
				return;
			}

			this.pagination.current = 1;
			this.getTableData();
		},
		handleClose(removedTag) {
			let delIndex = this.rowSelectionMemberList.indexOf(removedTag);
			let delSelectItem = this.selectedMemberKeys.indexOf(removedTag.id);
			this.rowSelectionMemberList.splice(delIndex, 1);
			this.selectedMemberKeys.splice(delSelectItem, 1);
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedMemberKeys = selectedRowKeys;
			selectedRows.forEach((item) => {
				let hasArr = this.rowSelectionMemberList.filter((row) => {
					return row.id === item.id;
				});
				if (!hasArr.length) {
					// 去掉重复的
					this.rowSelectionMemberList.push(item);
				}
			});
			let isDelect = false;
			this.rowSelectionMemberList.forEach((list) => {
				// 取消选中删除
				isDelect = false;
				this.selectedMemberKeys.forEach((row) => {
					if (list.id === row) {
						isDelect = true;
					}
				});
				if (!isDelect) {
					this.rowSelectionMemberList = this.rowSelectionMemberList.filter((data) => {
						return data.id !== list.id;
					});
				}
			});
		},
		handleTableChange(pagination) {
			this.pagination.current = pagination;
			this.getTableData();
		},
		onShowSizeChange(pagination, size) {
			this.pagination.current = 1;
			this.pagination.pageSize = size;
			this.getTableData();
		},
		handleAfterClose() {
			this.isByDepartmentSelect = false;
			this.selectedDepartment = [];
			this.rowSelectionMemberList = [];
			this.selectedMemberKeys = [];
			this.search = {
				name: '',
				deptId: undefined
			};
		},
		close() {
			// eslint-disable-next-line vue/require-explicit-emits
			this.$emit('close', false);
		}
	}
};
</script>

<style lang="less" scoped>
.member-content {
	display: flex;
	padding: 10px;
	.member-table {
		width: 70%;
		border: 1px solid #eee;
		.table-search {
			margin: 10px 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}
	.member-list {
		width: 30%;
		border: 1px solid #eee;
		margin-left: 10px;
	}
	.table-flag {
		background-color: #efefef;
		text-align: center;
		line-height: 40px;
		font-size: 16px;
		color: #333;
		border-bottom: 1px solid #eee;
	}
	.page-btn {
		text-align: right;
		margin: 10px 0;
	}
}

// 已选择
.selected-view {
	height: 532px;
	overflow: auto;
}

.select-staff .ant-select-selection__rendered {
	// li {
	//   display: none;
	// }
}
</style>
